<template>
  <div>
    <div class="flex w-full flex-wrap gap-16">
      <div class="preViewImg" v-for="(item, index) in valueList">
        <div class="img-box">
          <img :src="item" alt="" />
        </div>
        <div class="mark flex_aic_jcc gap-16">
          <el-icon
            class="cursor-pointer"
            size="16"
            color="#ffffff"
            @click="handlepreview(item)"
            ><View
          /></el-icon>
          <el-icon
            class="cursor-pointer"
            size="16"
            color="#ffffff"
            @click="handleDelete(index)"
            ><Delete
          /></el-icon>
        </div>
      </div>
      <div
        class="upload-box"
        @click="handleAdd"
        v-if="valueList.length < limit"
      >
        <img v-if="value" :src="value" alt="" />
        <el-icon v-else size="26" color="#999"><Plus /></el-icon>
      </div>
    </div>
    <div class="fs-12 color-666666 mt8">{{ tip }}</div>

    <Dialog
      v-model="show"
      :title="$t('pickPicture.选择图片')"
      width="1200px"
      @close="handleClose"
      @confirm="handleConfirm"
      :append-to-body="true"
      :z-index="2999"
    >
      <div class="flex" style="height: 500px">
        <div style="width: 200px">
          <el-button
            type="primary"
            style="width: 100%"
            @click="showAddGroup = true"
          >
            <el-icon><Plus /></el-icon>
            <span>{{ $t("pickPicture.添加分组") }}</span>
          </el-button>
          <div class="mt12 overflow-y-auto" style="height: calc(100% - 50px)">
            <div
              class="groupItem"
              :class="{ active: activeGroup === 'all' }"
              @click="activeGroup = 'all'"
            >
              {{ $t("pickPicture.全部") }}
            </div>
            <div
              class="groupItem flex_aic_jcsb"
              v-for="(item, index) in groupList"
              :class="{ active: activeGroup === item.id }"
              @click="activeGroup = item.id"
            >
              <span class="line-1" style="width: 100px">{{ item.name }}</span>
              <div class="flex_aic opeaArea">
                <el-button
                  type="primary"
                  link
                  @click.stop="handleEditGroup(item)"
                  >{{ $t("pickPicture.编辑") }}</el-button
                >
                <el-button
                  class="ml4"
                  type="primary"
                  link
                  @click.stop="handleRemoveGroup(item)"
                  >{{ $t("pickPicture.删除") }}</el-button
                >
              </div>
            </div>
          </div>
        </div>
        <div class="flex1 rightArea ml12 pl12">
          <div class="flex_aic gap-12">
            <UploadButton
              v-if="activeGroup !== 'all'"
              v-model="uploadList"
              @success="handleUploadSuccess"
            />
            <el-dropdown
              @command="handleBatchUpdateGroup"
              :teleported="false"
              max-height="160px"
            >
              <el-button>
                {{ $t("pickPicture.批量修改分组") }}<el-icon class="el-icon--right"
                  ><arrow-down
                /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in groupList"
                    :key="item.id"
                    :command="item.id"
                    >{{ item.name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-popconfirm
              :title="$t('pickPicture.确定删除吗')"
              @confirm="handleBatchDelete"
              :teleported="false"
              width="300px"
            >
              <template #reference>
                <el-button type="danger">{{ $t("pickPicture.批量删除") }}</el-button>
              </template>
            </el-popconfirm>
          </div>
          <template v-if="imageList.length > 0">
            <div
              class="flex flex-wrap gap-12 mt16 overflow-y-auto"
              style="max-height: calc(100% - 60px)"
            >
              <div
                class="flex_fdc imgItem"
                v-for="item in imageList"
                :key="item.id"
              >
                <div class="img-box cursor-pointer" @click="selectImg(item)">
                  <div
                    class="check-box flex_aic_jcc"
                    v-if="selectImgList.includes(item.imageUrl)"
                  >
                    <el-icon color="#fff" size="14"><Check /></el-icon>
                  </div>
                  <img :src="item.imageUrl" alt="" />
                </div>
                <div class="fs-14 mt4 w-full line-1">{{ item.imageName }}</div>
                <div class="flex_aic_jcsb">
                  <div class="fs-12 color-999999">
                    {{ moment(item.updateTime).format("YYYY-MM-DD") }}
                  </div>
                  <div class="flex gap-12 opeaRow">
                    <el-icon
                      class="cursor-pointer"
                      @click="handlepreview(item.imageUrl)"
                      ><View
                    /></el-icon>
                    <el-icon
                      class="cursor-pointer"
                      @click="handleDelete2(item.id)"
                      ><Delete
                    /></el-icon>
                  </div>
                </div>
              </div>
            </div>
            <div class="flex_aic_jcc mt12">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="getImageList"
                :teleported="false"
              />
            </div>
          </template>
          <div class="flex_aic_jcc mt32 color-999999" v-else>
            <span>{{ $t("pickPicture.暂无图片") }}</span>
          </div>
        </div>
      </div>
    </Dialog>

    <Dialog
      v-model="showAddGroup"
      :title="$t('pickPicture.新建分组')"
      width="600px"
      @close="closeAddGroup"
      @confirm="confirmAddGroup"
      :append-to-body="true"
      :z-index="3001"
    >
      <el-form
        :model="groupform"
        :rules="groupRules"
        ref="groupFormRef"
        label-width="200px"
      >
        <el-form-item :label="$t('pickPicture.分组名称')" prop="name">
          <el-input v-model="groupform.name" :placeholder="$t('pickPicture.请输入分组名称')" />
        </el-form-item>
        <el-form-item :label="$t('pickPicture.排序')" prop="sort">
          <el-input-number
            v-model="groupform.sort"
            :min="0"
            :max="100"
            :step="1"
          />
        </el-form-item>
      </el-form>
    </Dialog>

    <el-image-viewer
      v-if="showPreview"
      :url-list="previewSrcList"
      show-progress
      :initial-index="previewIndex"
      @close="showPreview = false"
      :preview-teleported="true"
      :teleported="true"
      :z-index="3000"
    />
  </div>
</template>
<script setup>
import { ref, watch } from "vue";
import Dialog from "./dialog.vue";
import {
  UploadFilled,
  Plus,
  View,
  Delete,
  Check,
  ArrowDown,
} from "@element-plus/icons-vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import UploadFile from "@/components/UploadFile.vue";
import UploadButton from "@/components/UploadButton.vue";
import moment from "moment";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const show = ref(false);
const showPreview = ref(false);
const previewSrcList = ref([]);
const previewIndex = ref(0);
const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  tip: {
    type: String,
    default: "",
  },
});
const valueList = defineModel();
const groupform = ref({
  id: "",
  name: "",
  sort: 0,
});
const groupRules = ref({
  name: [{ required: true, message: t("pickPicture.请输入分组名称"), trigger: "blur" }],
  sort: [{ required: true, message: t("pickPicture.请输入排序"), trigger: "blur" }],
});
const groupFormRef = ref(null);
const showAddGroup = ref(false);
const groupList = ref([]);
const activeGroup = ref("all");
const uploadList = ref([]);
const imageList = ref([]);
const editImgIndex = ref(-1);
const selectImgList = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

const handleUploadSuccess = (response, file, uploadFiles) => {
  const arr = uploadFiles.map((v) => ({
    imageName: v.name,
    imageUrl: v.url,
    classifyId: activeGroup.value,
    sort: 0,
    type: 1,
  }));
  Api.addTenantImages_saveList(arr).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: t("pickPicture.保存成功"),
        type: "success",
        duration: 3000,
        customClass: "z-index-3002",
      });
      getImageList();
    }
  });
};
const handleConfirm = () => {
  if (valueList.value.length + selectImgList.value.length > props.limit) {
    ElMessage({
      message: t("pickPicture.最多选择") + (props.limit - valueList.value.length) + t("pickPicture.张图片"),
      type: "warning",
      duration: 3000,
      customClass: "z-index-3002",
    });
    return;
  }
  valueList.value.push(...selectImgList.value);
  handleClose();
};
const handleClose = () => {
  selectImgList.value = [];
  editImgIndex.value = -1;
  show.value = false;
};
const handleEditGroup = (item) => {
  showAddGroup.value = true;
  groupform.value = {
    ...item,
  };
};
const handleRemoveGroup = (item) => {
  Api.tenantImagesClassifyDelete([item.id]).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: t("pickPicture.删除成功"),
        type: "success",
        duration: 3000,
        customClass: "z-index-3002",
      });
      getGroupList();
    }
  });
};
const closeAddGroup = () => {
  groupFormRef.value.resetFields();
  showAddGroup.value = false;
  groupform.value = {
    id: "",
    name: "",
    sort: 0,
  };
};
const confirmAddGroup = () => {
  groupFormRef.value.validate((valid) => {
    if (valid) {
      Api[
        groupform.value.id
          ? "tenantImagesClassifyUpdate"
          : "tenantImagesClassifyAdd"
      ]({
        ...groupform.value,
      }).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: t("pickPicture.操作成功"),
            type: "success",
            duration: 3000,
            customClass: "z-index-3002",
          });
          closeAddGroup();
          getGroupList();
        }
      });
    }
  });
};

const getGroupList = () => {
  const user = Storage.get("user", true);
  Api.tenantImagesClassifyList({
    // tenantId: user.tenant.id,
  }).then((res) => {
    groupList.value = (res.data?.content || []).sort((a, b) => a.sort - b.sort);
  });
};

//获取图片列表
const getImageList = () => {
  Api.getTenantImages({
    page: currentPage.value - 1,
    size: pageSize.value,
    type: 1,
    classifyId: activeGroup.value === "all" ? "" : activeGroup.value,
  }).then((res) => {
    imageList.value = res.data?.content || [];
    total.value = +res.data?.totalElements || 0;
  });
};

const handleSizeChange = (size) => {
  currentPage.value = 1;
  getImageList();
};

const selectImg = (item) => {
  if (selectImgList.value.includes(item.imageUrl)) {
    selectImgList.value = selectImgList.value.filter(
      (imageUrl) => imageUrl !== item.imageUrl
    );
  } else {
    selectImgList.value.push(item.imageUrl);
  }
};

// 新增选择图片
const handleAdd = () => {
  show.value = true;
};

// 预览图片
const handlepreview = (item) => {
  previewSrcList.value = [item];
  previewIndex.value = 0;
  showPreview.value = true;
};

// 删除所选图片
const handleDelete = (index) => {
  valueList.value.splice(index, 1);
};

// 删除图片库中的图片
const handleDelete2 = (id) => {
  Api.deleteTenantImages([id]).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: t("pickPicture.删除成功"),
        type: "success",
        duration: 3000,
        customClass: "z-index-3002",
      });
      getImageList();
    }
  });
};

const handleBatchUpdateGroup = (id) => {
  console.log(id);
  if (selectImgList.value.length === 0) {
    ElMessage({
      message: t("pickPicture.请先选择图片"),
      type: "warning",
      duration: 3000,
      customClass: "z-index-3002",
    });
    return;
  }
  const ids = imageList.value
    .filter((item) => selectImgList.value.includes(item.imageUrl))
    .map((item) => item.id);
  const posts = ids.map((_id) => {
    return Api.updateTenantImages({
      id: _id,
      classifyId: id,
    });
  });
  Promise.all(posts).then((res) => {
    if (res.every((item) => item.status === 200)) {
      ElMessage({
        message: t("pickPicture.修改成功"),
        type: "success",
        duration: 3000,
        customClass: "z-index-3002",
      });
      getImageList();
    }
  });
};

const handleBatchDelete = () => {
  if (selectImgList.value.length === 0) {
    ElMessage({
      message: t("pickPicture.请先选择图片"),
      type: "warning",
      duration: 3000,
      customClass: "z-index-3002",
    });
    return;
  }
  const ids = imageList.value
    .filter((item) => selectImgList.value.includes(item.imageUrl))
    .map((item) => item.id);
  Api.deleteTenantImages(ids).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: t("pickPicture.删除成功"),
        type: "success",
        duration: 3000,
        customClass: "z-index-3002",
      });
      getImageList();
    }
  });
};

watch(
  () => show.value,
  (val) => {
    if (val) {
      getGroupList();
      getImageList();
    }
  }
);

watch(
  () => activeGroup.value,
  (val) => {
    getImageList();
  }
);
</script>
<style scoped>
.upload-box {
  width: 146px;
  height: 146px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #f5f7fa;
}

.groupItem {
  height: 36px;
  line-height: 36px;
  padding: 0 10px;
  cursor: pointer;
  &.active {
    color: var(--el-color-primary);
    background-color: #f0faff;
  }

  .opeaArea {
    display: none;
  }

  &:hover {
    color: var(--el-color-primary);
    background-color: #f0faff;
    .opeaArea {
      display: flex;
    }
  }
}

.rightArea {
  border-left: 1px solid #ececec;
}

.imgItem {
  width: 148px;

  .img-box {
    width: 148px;
    height: 148px;
    border: 1px solid #ececec;
    border-radius: 8px;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      vertical-align: middle;
      border-radius: 8px;
    }
    .check-box {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 20px;
      height: 20px;
      background-color: var(--el-color-primary);
    }
  }
  .opeaRow {
    display: none;
  }

  &:hover {
    .opeaRow {
      display: flex;
    }
  }
}

.preViewImg {
  width: 146px;
  height: 146px;
  border-radius: 8px;
  position: relative;
  /* img {
    width: 100%;
    height: 100%;
    vertical-align: middle;
  } */
  .img-box {
    width: 146px;
    height: 146px;
    border: 1px solid #ececec;
    border-radius: 8px;
    img {
      width: 100%;
      height: 100%;
      vertical-align: middle;
      border-radius: 8px;
    }
  }

  &:hover {
    .mark {
      display: flex;
    }
  }

  .mark {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 1;
    display: none;
    background-color: rgba(0, 0, 0, 0.5);
  }
}
</style>
